// order.js
var app = getApp();
var common = require("../../../common/utils.js");
var bmap = require('../../../common/bmap-wx.min.js');
// 获取当前一小时后的时间
function returnDate() {
  let date = new Date();
  let hours = (date.getHours() + 1) + ':' + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  return hours;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    date: app.startdate,
    contacts: '',
    contactschoose: '',
    iscontactschoose: false,
    mainpage: true,
    contactpage: false,
    selected: false,
    appends: false,
    uppoint: {},
    linename: '',
    show: true,
    isAgree: true,
    explainpage: false,
    appColor: app.appColor,
    AtAddress: "定位中..."
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function(options) {
    var that = this;
    this.setData({
      linename: options.linename,
      pathid: options.pathid,
      bag: options.bag,
      packprice: options.packprice,
      spellprice: options.spellprice,
      description: options.description,
      radioItems: [{
          name: '拼车￥' + options.spellprice,
          value: '0',
          checked: options.bag == '0' ? true : false
        },
        {
          name: '包车￥' + options.packprice,
          value: '1',
          checked: options.bag == '1' ? true : false
        }
      ],
    });
    this.getTakeman();

    // 百度地图定位获取当前位置信息
    var BMap = new bmap.BMapWX({
      ak: 'D097238894b7c9f3ddf8fd92be560188'
    });
    var success = function(data) {
      that.setData({
        AtAddress: data.wxMarkerData[0].address,
      });
      that.data.uppoint.address = data.wxMarkerData[0].address;
      that.data.uppoint.longitude = data.wxMarkerData[0].longitude;
      that.data.uppoint.latitude = data.wxMarkerData[0].latitude;
    }
    var fail = function(data) {}
    BMap.regeocoding({
      fail: fail,
      success: success
    });
  },
  // 提示框
  AlertNames: function() {
    let that = this;
    wx.showModal({
      content: '请确认信息填写是否完整',
      showCancel: false,
      success: function(res) {
        if (res.confirm) {
          that.setData({
            reserve: true
          })
        }
      }
    });
  },
  selectDate: function() {
    wx.navigateTo({
      url: '/pages/calendar/calendar'
    });
  },
  order: function(e) {
    var that = this;
    this.setData({
      reserve: false
    })
    var arr = [];
    if (this.data.contactschoose == '') {
      this.AlertNames();
      return
    }
    if (this.data.contactschoose != null && typeof(this.data.contactschoose) != undefined) {
      this.data.contactschoose.forEach(function(item) {
        arr.push(item.TakeManId)
      })
    }
    var TakeManId = arr.join(',');
    // 是否拼车
    var IsSharing = this.data.radioItems[0].checked == true ? true : false;
    if (this.data.time != '' && this.data.uppoint != '' && this.data.getSite && this.data.contactschoose != '') {
      wx.request({
        url: app.serviceurl + 'CarRental/CarRentalBuildOrder',
        header: {
          Authorization: "Bearer " + app.accesstoken
        },
        data: {
          CarLineID: this.data.pathid,
          TakemanID: TakeManId,
          UpPointName: this.data.uppoint.address,
          UpPointLong: this.data.uppoint.longitude,
          UpPointLat: this.data.uppoint.latitude,
          DownPointName: this.data.getSite,
          DownPointLong: this.data.lng,
          DownPointLat: this.data.lat,
          IsSharing: IsSharing,
          StartDate: this.data.date,
          StartTime: this.data.time
        },
        dataType: 'json',
        success: function(res) {
          let newData = new Object;
          newData.data = res.data;
          newData.IsSharing = IsSharing;
          var succeed;
          if (res.data.Result == false) {
            wx.setStorage({
              key: 'orderMess',
              data: res.data,
            })
            succeed = false;
          } else {
            wx.setStorage({
              key: 'newOrderMess',
              data: newData,
            })
            succeed = true;
          }
          wx.navigateTo({
            url: '../orderconfirm/orderconfirm?issharing=' + IsSharing + '&succeed=' + succeed,
          });
        },
        fail: function() {
          console.log("调用失败");
        }
      })
    } else {
      this.AlertNames();
    }
  },

  getTakeman: function() {
    var that = this;
    wx.request({
      url: app.serviceurl + 'Member/GetTakeman',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {},
      dataType: 'json',
      success: function(res) {
        if (!res.data.Result) {
          return;
        };
        if (res.data.TakeManList != null && typeof(res.data.TakeManList) != undefined) {
          res.data.TakeManList.forEach(function(item) {
            item.TakeManPhone = item.TakeManPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
            item.TakeManCardId = item.TakeManCardId.replace(/(\d{6})\d{4}(\d{4})/, '$1****$2');
          })
          for (var i = 0, lenI = res.data.TakeManList.length; i < lenI; ++i) {
            res.data.TakeManList[i].TakeManPhone = false;
          }
        }

        that.setData({
          contacts: res.data.TakeManList
        });
      },
      fail: function() {
        console.log("调用失败");
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    this.getTakeman();
    this.setData({
      date: app.startdate,
      reserve: true,
      time: returnDate(),
    })
    wx.getStorage({
      key: 'getSite',
      success: function(res) {
        that.setData({
          getSite: res.data.site,
          lat: res.data.lat,
          lng: res.data.lng,
        })
      }
    });
    // if (app.carHint) {
    //   wx.showModal({
    //     title: "预定成功",
    //     content: "请在未完成订单中处理该订单，5分钟内无法重复预定！",
    //     showCancel: false,
    //     confirmText: "确定",
    //     complete: function (res) {
    //       app.carHint = false;
    //     }
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  bindTimeChange: function(e) {
    this.setData({
      time: e.detail.value,
      show: true
    })
  },

  radioChange: function(e) {
    var radioItems = this.data.radioItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == e.detail.value;
    }
    this.setData({
      radioItems: radioItems
    });
  },
  adress: function() {
    wx.navigateTo({
      url: '../adress/adress',
    })
  },
  upaddress: function() {
    var that = this;
    wx.chooseLocation({
      success: function(res) {
        that.setData({
          uppoint: res,
          AtAddress: res.name
        });

      },
      fail(err) {
        console.log(err)
      }
    })
  },
  downaddress: function() {
    var that = this;
    wx.navigateTo({
      url: '../getSite/getSite',
    })
  },
  choosecontact: function(e) {
    this.setData({
      mainpage: false,
      contactpage: true
    });
  },
  mustknow: function(e) {
    this.setData({
      mainpage: false,
      explainpage: true
    })
  },
  explainconfirm: function(e) {
    this.setData({
      mainpage: true,
      explainpage: false,
    });
  },
  returns: function() {
    this.setData({
      mainpage: true,
      contactpage: false,
      appends: false
    });
  },

  checkboxChange: function(e) {
    var contacts = this.data.contacts;
    for (var i = 0, lenI = contacts.length; i < lenI; ++i) {
      if (contacts[i].TakeManId == e.currentTarget.dataset.takeman) {
        contacts[i].TakeManPhone = contacts[i].TakeManPhone == true ? false : true;
      }
      if (contacts[i].TakeManPhone == true) {
        this.setData({
          selected: true
        });
      }
    }
    this.setData({
      contacts: contacts
    });
  },

  chooseconfirm: function(e) {
    var contacts = this.data.contacts;
    var tmp = [];
    var count = 0;
    this.setData({
      iscontactschoose: false
    });
    for (var i = 0, lenI = contacts.length; i < lenI; ++i) {
      if (contacts[i].TakeManPhone == true) {
        count++;
        tmp.push(contacts[i]);
        this.setData({
          iscontactschoose: true
        });
      }
    }
    app.takemaninfo = tmp;
    var moeny = count * app.businfo.Price;
    this.setData({
      mainpage: true,
      contactpage: false,
      contactschoose: tmp,
      totalmoeny: moeny
    });
  },

  append: function() {
    // this.setData({
    //   appends: true
    // })
    wx.navigateTo({
      url: '/pages/contact/addContact/addContact',
    })
  },
  cancel: function() {
    this.setData({
      appends: false
    })
  },
  // 添加联系人
  // 获取input值
  userName: function(e) {
    this.data.TakemanName = e.detail.value
  },
  cardId: function(e) {
    this.data.TakemanCardID = e.detail.value
  },
  phone: function(e) {
    this.data.TakemanPone = e.detail.value
  },



  bindAgreeChange: function(e) {
    this.setData({
      isAgree: !e.currentTarget.dataset.isagree,
    });
  },

})